#import "OmPersonalSettingVC.h"
#import "OmPersonalSettingVCTableViewCell.h"
#import "OmPersonalSettingVCTableViewCellTypeSex.h"
#import "OmPersonalSettingVCSectionHeaderView.h"
#import "OmPersonalSettingVCAvatarView.h"
#import "TZImagePickerController.h"
#import "NoveltyApiPhotosUploadModel.h"
#import "EditUserModel.h"
#import "OmBirthdayView.h"
#import "OmPersonEditAlertView.h"
#import "UserApiEditUserInfoModel.h"
#import "OmPersonIncomView.h"
#import "OmPersonSignVC.h"
#import "OmPersonCharacterVC.h"
#define CellReuseID @"OmPersonalSettingVCTableViewCell"
#define CellReuseIDTypeSex @"OmPersonalSettingVCTableViewCellTypeSex"
typedef NS_ENUM(NSUInteger, UserMessageEditType) {
    UserMessageEdit_UserName = 0,
    UserMessageEdit_Sex,
    UserMessageEdit_Birthday,
    UserMessageEdit_Height,
    UserMessageEdit_Weight,
    UserMessageEdit_Love,
    UserMessageEdit_Character,
    UserMessageEdit_Country,
    UserMessageEdit_City,
    UserMessageEdit_Culture,
    UserMessageEdit_Occupation,
    UserMessageEdit_Income,
    UserMessageEdit_Motto
};
@interface OmPersonalSettingVC () <UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate>
@property (nonatomic, assign) UserMessageEditType editType;
@property (nonatomic, copy) NSString *editContent;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *contentArray;
@property (nonatomic, assign) NSInteger sex;
@end
@implementation OmPersonalSettingVC
#pragma mark - data
- (NSArray *)getDataArray {
    return @[@[@{@"title":ASLocalizedString(@"用户名"),
                 @"image":@"OmSettingName",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeNickName"
                 },
               @{@"title":ASLocalizedString(@"性别"),
                 @"image":@"OmSettingSex",
                 @"type":@"sex",
                 @"selector":@"cellEventChangeSex"
                 },
               @{@"title":ASLocalizedString(@"生日"),
                 @"image":@"OmSettingBirthday",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeBirthday"
                 },
               @{@"title":ASLocalizedString(@"身高"),
                 @"image":@"OmSettingHeight",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeHeight"
                 },
               @{@"title":ASLocalizedString(@"体重"),
                 @"image":@"OmSettingWeight",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeWeight"
                 },
               @{@"title":ASLocalizedString(@"感情"),
                 @"image":@"OmSettingLove",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeLove"
                 },
               @{@"title":ASLocalizedString(@"性格"),
                 @"image":@"OmSettingFace",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeCharacter"
                 }],
             @[@{@"title":ASLocalizedString(@"国家"),
                 @"image":@"OmSettingCountry",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeCountry"
                 },
               @{@"title":ASLocalizedString(@"城市"),
                 @"image":@"OmSettingCity",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeCity"
                 }],
             @[@{@"title":ASLocalizedString(@"文化"),
                 @"image":@"OmSettingBook",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeCulture"
                 },
               @{@"title":ASLocalizedString(@"职业"),
                 @"image":@"OmSettingWork",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeOccupation"
                 },
               @{@"title":ASLocalizedString(@"收入"),
                 @"image":@"OmSettingMoney",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeIncome"
                 },
               @{@"title":ASLocalizedString(@"座右铭"),
                 @"image":@"OmSettingWord",
                 @"type":@"normal",
                 @"selector":@"cellEventChangeMotto"
                 }]];
}
#pragma mark - Event
- (void)refreshSelf {
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"edit_user_info"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"to_user_id"] = self.ID;
    [CYNET POST:url parameters:parameters responseCache:nil success:^(id responseObject) {
        UserApiEditUserInfoModel *model = [UserApiEditUserInfoModel mj_objectWithKeyValues:responseObject];
        self.sex = model.sex;
        NSMutableArray<OmCharacterModel *> *characterModels = model.u_character;
        NSMutableString *charactersString = [NSMutableString string];
        for (OmCharacterModel *model in characterModels) {
            [charactersString appendString:isCurrentLanguageChinese?model.z_name:model.e_name];
            [charactersString appendString:@" "];
        }
        self.contentArray = @[@[model.user_nickname,
                                @"",
                                model.birthdayStr,
                                model.auth_form_record.height,
                                model.auth_form_record.weight,
                                model.auth_form_record.emotion,
                                charactersString
                                ],
                              @[model.auth_form_record.country,
                                model.auth_form_record.city
                                ],
                              @[model.auth_form_record.education,
                                model.auth_form_record.occupation,
                                model.auth_form_record.income,
                                model.auth_form_record.sign]
                              ];
        OmPersonalSettingVCAvatarView *avatarView = self.tableView.tableHeaderView;
        avatarView.toUserImageUrl = model.avatar;
        [self.tableView reloadData];
        
    } failure:^(NSString *error) {
    } hasCache:NO];
}
- (void)touchEventChangeAvatar {
     if (![self.ID isEqualToString:curUser.id]) return;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count > 0) [self changeAvatarToImage:photos[0]];
    }];
    imagePickerVc.showSelectBtn = YES;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark - 修改
- (void)cellEventChangeWeight {
    _editType = UserMessageEdit_Weight;
    [self showAlertInputView:ASLocalizedString(@"修改体重") placeholder:ASLocalizedString(@"请输入体重(kg)")];
}
- (void)cellEventChangeNickName {
    _editType = UserMessageEdit_UserName;
    [self showAlertInputView:ASLocalizedString(@"修改用户名") placeholder:ASLocalizedString(@"请输入新的用户名")];
}
- (void)cellEventChangeSex {
    _editType = UserMessageEdit_Sex;
}
- (void)cellEventChangeBirthday {
    _editType = UserMessageEdit_Birthday;
    __weak typeof(self) weakSelf = self;
    [OmBirthdayView showInWindowWithBlock:^(NSDate * _Nonnull date) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        NSString *time = NSStringFormat(@"%.0f",[date timeIntervalSince1970]);
        self.editContent = time;
        [strongSelf loadRequest];
    }];
}
- (void)cellEventChangeHeight {
    _editType = UserMessageEdit_Height;
    [self showAlertInputView:ASLocalizedString(@"修改身高") placeholder:ASLocalizedString(@"请输入身高(cm)")];
}
- (void)cellEventChangeLove {
    _editType = UserMessageEdit_Love;
    __weak typeof(self) weakSelf = self;
    [OmPersonEditAlertView showInViewWithType:0 selectBlock:^(NSString * _Nonnull content) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        self.editContent = content;
        [strongSelf loadRequest];
    }];
}
- (void)cellEventChangeCharacter {
    _editType = UserMessageEdit_Character;
    OmPersonCharacterVC *characterVC = [[OmPersonCharacterVC alloc]init];
    [self.navigationController pushViewController:characterVC animated:YES];
}
- (void)cellEventChangeCountry {
    _editType = UserMessageEdit_Country;
    [self showAlertInputView:ASLocalizedString(@"修改国家") placeholder:ASLocalizedString(@"请输入国家")];
}
- (void)cellEventChangeCity {
    _editType = UserMessageEdit_City;
    [self showAlertInputView:ASLocalizedString(@"修改城市") placeholder:ASLocalizedString(@"请输入城市")];
}
- (void)cellEventChangeCulture {
    _editType = UserMessageEdit_Culture;
    __weak typeof(self) weakSelf = self;
    [OmPersonEditAlertView showInViewWithType:1 selectBlock:^(NSString * _Nonnull content) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        self.editContent = content;
        [strongSelf loadRequest];
    }];
}
- (void)cellEventChangeOccupation {
    _editType = UserMessageEdit_Occupation;
    [self showAlertInputView:ASLocalizedString(@"修改职业") placeholder:ASLocalizedString(@"请输入您的职业")];
}
- (void)cellEventChangeIncome {
    _editType = UserMessageEdit_Income;
    __weak typeof(self) weakSelf = self;
    [OmPersonIncomView showInViewWithBlock:^(NSString * _Nonnull content) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        self.editContent = content;
        [strongSelf loadRequest];
    }];
}
- (void)cellEventChangeMotto {
    _editType = UserMessageEdit_Motto;
    OmPersonSignVC *signVC = [[OmPersonSignVC alloc]init];
    [self.navigationController pushViewController:signVC animated:YES];
}
- (void)showAlertInputView:(NSString *)title placeholder:(NSString *)placeholder {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = placeholder;
        textField.textColor = HexadecimalColor(@"#333333");
        textField.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:ASLocalizedString(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *inputTextField = alertController.textFields.firstObject;
        [self completeInput:inputTextField.text];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:ASLocalizedString(@"取消") style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)completeInput:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (!StrValid(value)) {
        [MBProgressHUD showErrorMessage:ASLocalizedString(@"请先输入非空格内容")];
        return;
    }
    if (_editType == UserMessageEdit_Weight || _editType == UserMessageEdit_Height) {
        if (![self isPureFloat:value] && ![self isPureInt:value]) {
            [MBProgressHUD showErrorMessage:ASLocalizedString(@"请输入数字")];
            return;
        }
    }
    self.editContent = value;
    [self loadRequest];
}
#pragma mark - 数据判断
#pragma mark 判断字符串是否为浮点数
- (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
#pragma mark 判断是否为整形
- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
#pragma mark - 网络加载
- (void)loadRequest {
    [[HUDHelper sharedInstance] loading:ASLocalizedString(@"更新中...")];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"save_user_field"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"key_name"] = [self getLoadingParamKey];
    parameters[@"key_value"] = self.editContent;
    [CYNET POST:url parameters:parameters responseCache:nil success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showSuccessMessage:ASLocalizedString(NSStringFormat(@"%@修改成功",[self getEventTitle]))];
        });
        [self changeSuccess];
        [self refreshSelf];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUD];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD showTipMessageInView:error];
        });
    } hasCache:NO];
}
- (void)changeSuccess {
    if (_editType == 0) {
         curUser.user_nickname = self.editContent;
        [userManager saveUserInfo];
    }
}
- (NSString *)getLoadingParamKey {
    NSString *key = @"";
    switch (self.editType) {
        case 0:
            key = @"user_nickname";
            break;
        case 1:
            key = @"";
            break;
        case 2:
            key = @"birthday";
            break;
        case 3:
            key = @"height";
            break;
        case 4:
            key = @"weight";
            break;
        case 5:
            key = @"emotion";
            break;
        case 6:
            key = @"character";
            break;
        case 7:
            key = @"country";
            break;
        case 8:
            key = @"city";
            break;
        case 9:
            key = @"education";
            break;
        case 10:
            key = @"occupation";
            break;
        case 11:
            key = @"income";
            break;
        case 12:
            key = @"sign";
            break;
        default:
            break;
    }
    return key;
}
- (NSString *)getEventTitle {
    NSString *title = @"";
    switch (self.editType) {
        case 0:
            title = @"用户名";
            break;
        case 1:
            title = @"性别";
            break;
        case 2:
            title = @"生日";
            break;
        case 3:
            title = @"身高";
            break;
        case 4:
            title = @"体重";
            break;
        case 5:
            title = @"感情";
            break;
        case 6:
            title = @"性格";
            break;
        case 7:
            title = @"国家";
            break;
        case 8:
            title = @"城市";
            break;
        case 9:
            title = @"文化";
            break;
        case 10:
            title = @"职业";
            break;
        case 11:
            title = @"收入";
            break;
        case 12:
            title = @"座右铭";
            break;
        default:
            break;
    }
    return title;
}
#pragma mark - Method
- (void)changeAvatarToImage:(UIImage *)image {
    [[HUDHelper sharedInstance] loading:ASLocalizedString(@"头像上传中..")];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"uid"] = curUser.id;
    param[@"token"] = curUser.token;
    [PPNetworkHelper uploadImagesWithURL:[cyurl makeURLWithC:@"novelty_api" A:@"photos_upload"] parameters:param name:nil images:@[image] fileNames:nil imageScale:1 imageType:@"png" progress:^(NSProgress *progress) {
    } success:^(id responseObject) {
        if([[responseObject valueForKey:@"code"] intValue] == 1) {
            NSDictionary *dataDic = responseObject[@"data"];
            NSMutableArray<NSString *> *imageUrlArray = [NSMutableArray array];
            for (NSString *key in dataDic) {
                NoveltyApiPhotosUploadModel *model = [NoveltyApiPhotosUploadModel mj_objectWithKeyValues:dataDic[key]];
                [imageUrlArray addObject:model.img];
            }
            NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"save_user_field"];
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            parameters[@"key_name"] = @"avatar";
            parameters[@"key_value"] = imageUrlArray[0];
            [CYNET POST:url parameters:parameters responseCache:nil success:^(id responseObject) {
                [MBProgressHUD hideHUD];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD showSuccessMessage:ASLocalizedString(@"头像修改成功")];
                });
                [[[EditUserModel alloc] init] updateUserinfo:^(BOOL success) {
                    OmPersonalSettingVCAvatarView *view = self.tableView.tableHeaderView;
                    [view.headImageView setImage:image];
                }];
            } failure:^(NSString *error) {
                [MBProgressHUD hideHUD];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD showTipMessageInView:error];
                });
            } hasCache:NO];
        } else {
            [MBProgressHUD hideHUD];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD showTipMessageInView:[responseObject valueForKey:@"msg"]];
            });
        }
    } failure:^(NSError *error) {
    }];
}
#pragma mark - ConstructionScript
- (void)configSelf {
    [self setHiddenForTabBar:YES navigationBar:NO];
    self.title = ASLocalizedString([self.ID isEqualToString:curUser.id] ? @"编辑资料" : @"资料");
}
- (void)allocateComponents {
    self.tableView = (UITableView *)[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]
    .fp_delegate(self)
    .fp_dataSource(self)
    .fp_backgroundColor(HexadecimalColor(@"#F2F2F2"));
    [self.tableView registerNib:[UINib nibWithNibName:CellReuseID bundle:nil] forCellReuseIdentifier:CellReuseID];
    [self.tableView registerNib:[UINib nibWithNibName:CellReuseIDTypeSex bundle:nil] forCellReuseIdentifier:CellReuseIDTypeSex];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 77, 0, 0);
    OmPersonalSettingVCAvatarView *avatarView = [[OmPersonalSettingVCAvatarView alloc] initWithFrame:CGRectMake(0, 0, WINDOW_WIDTH, 83)];
    avatarView.ID = self.ID;
    self.tableView.tableHeaderView = avatarView;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchEventChangeAvatar)];
    [self.tableView.tableHeaderView addGestureRecognizer:recognizer];
    [self.view addSubview:self.tableView];
}
- (void)layoutComponents {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
}
#pragma mark - TableView
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 11;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSArray *sectionArray = [self getDataArray];
    return sectionArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionDataArray = [self getDataArray][section];
    return sectionDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *model = [self getDataArray][indexPath.section][indexPath.row];
    if ([model[@"type"] isEqualToString:@"sex"]) {
        OmPersonalSettingVCTableViewCellTypeSex *cell = [tableView dequeueReusableCellWithIdentifier:CellReuseIDTypeSex];
        if ((self.sex == 1 || self.sex == 2)) cell.sex = self.sex;
        cell.model = model;
        return cell;
    } else {
        OmPersonalSettingVCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellReuseID];
        if (![self.ID isEqualToString:curUser.id]) [cell hideRightIndexIcon];
        cell.model = model;
        if (self.contentArray) {
            [cell showContent:self.contentArray[indexPath.section][indexPath.row]];
        }
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 39;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *title;
    switch (section) {
        case 0:
            title = ASLocalizedString(@"个人资料");
            break;
        case 1:
            title = ASLocalizedString(@"位置");
            break;
        case 2:
            title = ASLocalizedString(@"更多资料");
            break;
    }
    OmPersonalSettingVCSectionHeaderView *headerView = [[OmPersonalSettingVCSectionHeaderView alloc] initWithTitle:title];
    return headerView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (![self.ID isEqualToString:curUser.id]) return;
    NSString *selectorString = [self getDataArray][indexPath.section][indexPath.row][@"selector"];
    SEL action = NSSelectorFromString(selectorString);
    if ([self respondsToSelector:action]) {
        PerformSelectorMuteWarning(self, action);
    }
}
@end
